﻿/*
 * KLF Headless Browser
 * Written by Kris Oye <kristianoye@gmail.com>
 * Copyright (C) 2011-2012.  All rights reserved.
 */
namespace KLF.Lib.Browser.DOM.TypedArray
{
    public class Int8Array : ITypedArray<sbyte>
    {
        public const int BYTES_PER_ELEMENT = sizeof(sbyte);

        #region Constructors

        public Int8Array(int length)
        {
            buffer = new ArrayBuffer(length * BYTES_PER_ELEMENT);
        }

        public Int8Array(ArrayBuffer _bufferIn)
        {
            buffer = _bufferIn;
        }

        #endregion

        #region Attributes

        private ArrayBuffer _buffer
        {
            get
            {
                return buffer as ArrayBuffer;
            }
        }

        #endregion

        #region ITypedArray<sbyte> Members

        public int length
        {
            get { return buffer.byteLength; }
        }

        public sbyte get(int index)
        {
            return (sbyte)_buffer._Buffer[index];
        }

        public void set(int index, sbyte value)
        {
            _buffer._Buffer[index] = (byte)value;
        }

        public sbyte this[int index]
        {
            get
            {
                return get(index);
            }
            set
            {
                set(index, value);
            }
        }

        public ITypedArray<sbyte> subarray(int begin)
        {
            return subarray(begin, 0);
        }

        public ITypedArray<sbyte> subarray(int begin, int end)
        {
            if (end == 0)
                end = length - 1;

            byte[] _newbuffer = new byte[end - begin];
            for (int i = begin, c = 0; i <= end; i++)
            {
                _newbuffer[c++] = _buffer._Buffer[i];
            }
            return new Int8Array(new ArrayBuffer(_newbuffer));
        }

        #endregion

        #region IArrayBufferView Members

        public IArrayBuffer buffer
        {
            get;
            private set;
        }

        public int byteOffset
        {
            get { throw new System.NotImplementedException(); }
        }

        public int byteLength
        {
            get { throw new System.NotImplementedException(); }
        }

        #endregion
    }
}
